const Service = require("egg").Service;
const axios = require("axios");

class WxGroupService extends Service {
  // 获取群聊列表，并更新数据库中的数据
  async updateGroupList(mywxid) {
    const { ctx } = this;
    await ctx.model.Wxgroup.deleteMany({ ownerWxid: mywxid });
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "getGroupList",
          data: {
            type: "2",
          },
        },
        {
          params: { wxid: mywxid },
        }
      );

      // 检查响应状态
      const datalist = response.data.result;

      // 使用 updateOne 配合 upsert 选项来更新或插入数据
      await Promise.all(
        datalist.map((obj) =>
          ctx.model.Wxgroup.updateOne(
            { wxid: obj.wxid }, // 查询条件
            {
              // 更新的数据
              $set: {
                ownerWxid: mywxid,
                nick: obj.nick,
                groupMemberNum: obj.groupMemberNum || 0,
                goupManger: obj.goupManger,
                avatarMinUrl: obj.avatarMinUrl,
                avatarMaxUrl: obj.avatarMaxUrl,
              },
            },
            { upsert: true } // 如果不存在则插入
          )
        )
      );
      return response.data;
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取失败:", error.message);
      return {
        success: false,
        message: "请求失败，请检查网络或接口状态",
      };
    }
  }

  async getGroupinfo(wxid) {
    const { ctx } = this;
    try {
      const wxgroup = await ctx.model.Wxgroup.findOne({ wxid });      
      return wxgroup;
    } catch (error) {
      ctx.logger.error("查询微信群记录失败:", error);
      throw new Error("查询群记录时发生异常");
    }
  }

  async getGroupList(mywxid, field, page, pageSize) {
    const { ctx } = this;    
    try {
      // 构建查询条件
      let query = { ownerWxid: mywxid };

      // 处理查询参数
      if (field.nick) {
        query.nick = new RegExp(field.nick, "i"); // i表示不区分大小写
      }
      if (field.tags && field.tags.length > 0) {
        query.tags = { $in: [field.tags] }; // 查找tags数组中包含指定tag的文档
      }
      if (field.issave !== undefined) {
        query.issave = field.issave;
      }
      if (field.isauto !== undefined) {
        query.isauto = field.isauto;
      }
      if (field.ischat !== undefined) {
        query.ischat = field.ischat;
      }
      if (field.isreceive !== undefined) {
        query.isreceive = field.isreceive;
      }
      // 计算跳过的文档数量
      const skip = (page - 1) * pageSize;

      // 获取总数
      const total = await ctx.model.Wxgroup.countDocuments(query);

      // 使用 skip 和 limit 实现分页查询
      const data = await ctx.model.Wxgroup.find(query)
        .skip(skip)
        .limit(pageSize)
        .sort({
          createTime: -1// 其次按创建时间降序
        })
        .exec();
      return {
        code: 20000,
        msg: "获取成功",
        data: {
          count: total,
          list: data,
        },
      };
    } catch (error) {
      // 捕获异常并返回错误信息
      this.logger.error("获取群聊信息失败:", error.message);
      return {
        code: 50000,
        msg: "请求失败，请检查网络或接口状态",
        data: {
          count: 0,
          list: []
        }
      };
    }
  }

  // 修改数据
  async editGroup(mywxid, wxid, field) {
    const { ctx } = this;
    // console.log( "editGroup", mywxid, wxid, field)
    try {
      const result = await ctx.model.Wxgroup.findOneAndUpdate(
        { ownerWxid: mywxid, wxid: wxid },
        { $set: field },
        { new: true }
      );
      
      if (!result) {
        throw new Error('数据库中未找到该群');
      }
      
      return result;
    } catch (error) {
      this.logger.error("更新好友状态失败:", error);
      throw error;
    }
  }

  // 退群
  async quitGroup(mywxid, wxid) {
    const { ctx } = this;
    try {
      const response = await axios.post(
        this.config.baseURL,
        {
          type: "quitGroup",
          data: {
            wxid
          },
        },
        {
          params: { wxid: mywxid },
        }
      );
      if (response.data.code === 200) {
        const result = await ctx.model.Wxgroup.deleteOne({
          wxid,
          ownerWxid: mywxid,
        });

        if (result.deletedCount === 0) {
          return {
            code: 50000,
            msg: "数据库中未找到该好友记录",
            data: null,
          };
        }
      
        if (!result) {
          throw new Error('未找到该群聊');
        }
        
        return result;
      }
    } catch (error) {
      this.logger.error("退群失败:", error);
      throw error;
    }
  }

  
}

module.exports = WxGroupService;
